package org.nf.trading.controller.app.order.alipay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.nf.trading.config.alipay.AliConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


@RestController
public class ReturnUrl {
    @RequestMapping("/alipay/returnUrl")
    public String returnUrlController(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws UnsupportedEncodingException {
        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, AliConfig.ALIPAY_PUBLIC_KEY, AliConfig.CHARSET,
                    AliConfig.sign_type);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // 调用SDK验证签名
        // 是否支付成功！
        // 转发视图
        if (signVerified) {

            // 相应的业务功能
            // 添加订单信息......
//            Order order = (Order)session.getAttribute("order");
//            OrderDAO dao = new OrderDAOImpl();
//            dao.updateOrder(order.orderId,1);
//
//            //把购物车的状态修改
//            ShoppingService service = new ShoppingServiceImpl();
//            service.updateShopPing(order.getUid(), order.getShopId());

            // 转发视图
//            forwardView = new ForwardView("http://localhost:9090/orderDetails");
            // 将数据放到请求作用域
//            forwardView.addObject("xxxx", "xxxx");

            return "http://localhost:9090/orderDetails";
        }
        return "";
    }
}
